#!/usr/bin/env python
#  -*- coding: UTF-8 -*-
import csv
import codecs
import hashlib
import sys, os
import json
import uuid

import datetime

reload(sys)
sys.setdefaultencoding('utf-8')
dirPath = os.path.join("static/upfile/")


def WriteCSV(data, header):
    struuid = str(uuid.uuid4())
    fileName = struuid + ".csv"
    filePath = dirPath + fileName
    with open(filePath, 'wb') as dstfile:  # 写入方式选择wb，否则有空行
        dstfile.write(codecs.BOM_UTF8)
        writer = csv.DictWriter(dstfile, fieldnames=header)
        writer.writeheader()  # 写入表头
        writer.writerows(data)  # 批量写入
    dstfile.close()
    return filePath
    # with open('test.csv', 'wb') as csvfile:
    #     csvfile.write(codecs.BOM_UTF8)
    #     spamwriter = csv.writer(csvfile, dialect='excel')
    #     for i in data:
    #         spamwriter.writerow(i)


def ReadCSV(fileName):
    list = []
    with open(fileName, 'r') as csvfile:
        reader = csv.DictReader(csvfile, fieldnames=None)  # fieldnames默认为None,如果所读csv文件没有表头，则需要指定
        # list_1 = [e for e in reader]  # 每行数据作为一个dict存入链表中
        for r in reader:
            # print type(r)
            for k in r:
                list.append(k)
                # print "dict[%s] =" % k,r[k]
                # d = json.loads(r)
                # print d.name
    csvfile.close()
    return list
    # for i in list_1:
    #     print i
    # with open('test.csv', 'rb') as csvfile:
    #     reader = csv.DictReader(csvfile)
    #     # rows = [row for row in reader]
    #     # print rows
    #     for row in reader:
    #         print row


def DelFiles(path):
    for root, dirs, files in os.walk(path):
        for name in files:
            if name == "test.csv":
                os.remove(os.path.join(root, name))
                # print("Delete File: " + os.path.join(root, name))


def CurFilePath():
    # 获取脚本路径
    path = sys.path[0]
    # 判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)


def SaveFile(file):
    struuid = str(uuid.uuid4())
    fileName = struuid + ".csv"
    try:
        destination = open(fileName, 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
    except Exception as e:
        pass
    return fileName


def UploadFiles(fileList):
    userdata = []
    try:
        if not fileList:
            raise Exception("没有上传文件")
        for f in fileList:
            # 上传文件，文件名生成guid.jpg,保留原文件名
            struuid = str(uuid.uuid4())
            originalFileName = f.name
            ext = originalFileName[originalFileName.index("."):len(originalFileName)]
            fName = struuid + ext
            destination = open(os.path.join("static/upfile/", fName), 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            fileUrl = '/static/upfile/'+fName
            info = {}
            info["file_name"] = originalFileName
            info["file_url"] = fileUrl
            userdata.append(info)
    except Exception as e:
        return {
            "status": 0,
            "message": u"文件上传失败:%s" % e.message,
            "data": []
        }
    return {
        "status": 1,
        "message": u"文件上传成功",
        "data": userdata
    }


# def UploadFile(request):
#     message = u"上传成功"
#     status = 1
#     userdata = []
#     if request.method == "POST":
#         myFile = request.FILES.getlist("myfile")
#         if not myFile:
#             # return HttpResponse("no files for upload!")
#         # 存储文件
#         userid = str(request.COOKIES['userid'])
#         for f in myFile:
#             d1 = datetime.datetime.now()
#             d2 = d1 + datetime.timedelta(hours=8)
#             locatime = d2.strftime("%Y-%m-%d %X")
#             sjc = d2.strftime("%Y-%m-%d-%H-%M-%S")
#             fName = sjc + '-' + f.name
#             destination = open(os.path.join("static/upfile/", fName), 'wb+')
#             for chunk in f.chunks():
#                 destination.write(chunk)
#             destination.close()
#             # return HttpResponse("ok")
#             try:
#                 # 生成MD5
#                 DirStrMD5 = 'static/upfile/'
#                 DirMD5 = DirStrMD5 + fName
#                 a_file = open(DirMD5, 'rb')
#                 m = hashlib.md5(a_file.read())
#                 a_file.close()
#                 hashMD5 = m.hexdigest()
#                 # 存储数据库数据准备
#                 tname = fName
#                 tmpName = tname.split('.', 1)
#                 filename = tmpName[0]
#                 filetype = tmpName[1]
#                 fileurl = '/static/upfile/' + tname
#                 DirMD5xx = 'static/upfile/' + fileurl
#                 filesize = getDocSize(DirMD5xx)
#                 absfiledir = DirStrMD5
#                 row = MySQLDB.CommitMySql(
#                     "INSERT INTO `t_dc_task_disease_file` (`create_user`,`name`,`status`,`description`,`url`) VALUES ('%s', '%s', 1, '%s', '%s')" % (
#                     userid, filename, filesize, fileurl))
#                 # 获取ID
#                 row = MySQLDB.SelectMySql(
#                     "SELECT `task_disease_file_id` FROM `t_dc_task_disease_file` WHERE name='%s' and create_user='%s';" % (
#                     filename, userid))
#                 IDnum = row[0][0]
#                 # 数据打包
#                 info = {}
#                 info["file_id"] = IDnum
#                 info["file_url"] = fileurl
#                 userdata.append(info)
#             except Exception as e:
#                 # return HttpResponse(e)
#                 message = u"上传失败"
#                 status = 0
#                 userdata = []
#         Sdata = {
#             "status": status,
#             "message": message,
#             "data": userdata
#         }
#         jsonstr = json.dumps(Sdata)
#         return HttpResponse(jsonstr, content_type="application/json")
#         # a = 1
#         # response = render_to_response('app_DQJC.html', {'flag': json.dumps(a)})
#         # return response


# 获取文件大小
def formatSize(bytes):
    try:
        bytes = float('%.2f' % bytes)
        kb = bytes / 1024
        return float('%.2f' % kb)
    except:
        return 0


def getDocSize(path):
    try:
        size = os.path.getsize(path)
        return formatSize(size)
    except:
        return 0
